'use strict';

import { createRouter, createWebHashHistory } from 'vue-router';
import NProgress from 'nprogress';

import pinia from '../store';
import { useAppStore } from '../store/modules';


// 菜单栏路由
import app from './modules/app';
import view from './modules/view';
export const routes = [...app, ...view];

const store = useAppStore(pinia);

const { VITE_PROJECT_NAME } = import.meta.env;

// 进度环显示/隐藏
NProgress.configure({
  easing: 'ease',
  minimum: 0.3,
  speed: 200,
  trickleSpeed: 200,
  showSpinner: false
});

const router = createRouter({
  history: createWebHashHistory(),
  routes: routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      if (from.meta.keepAlive) {
        from.meta.savedPosition = document.body.scrollTop;
      }
      return { x: 0, y: to.meta.savedPosition || 0 };
    }
  }
});

// 白名单路由
const whiteRoute = ['/login'];

router.beforeEach((to, from, next) => {
  NProgress.start();

  // 动态设置标题
  if (to.meta.title) document.title = `${to.meta.title} · ${VITE_PROJECT_NAME}`;

  if (store.token) {
    // 已登录，可跳转首页
    if (to.path === '/login') {
      next({ path: from.path });
      NProgress.done();
    } else {
      next();
    }
  } else {
    // 未登录，可访问白名单(登录页)，其他页面不可访问
    if (whiteRoute.includes(to.path)) {
      next();
    } else {
      next(`/login?redirect=${to.fullPath}&kleinkey=${Date.now()}`);
      NProgress.done();
    }
  }
});

router.afterEach(() => {
  window.scrollTo(0, 0);
  NProgress.done();
});

router.onError(() => {
  NProgress.done();
});

export default router;
